package com.test39_集合应用.service.impl;

import com.test39_集合应用.service.IDataService;
import com.test39_集合应用.vo.Privilege;
import com.test39_集合应用.vo.Role;
import com.test39_集合应用.vo.User;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Map;

public class DataServiceImpl implements IDataService {

    /** 数据存储 */
    @Override
    public void store(Object object) throws IOException {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(OBJECT_FILE));
        oos.writeObject(object);
        oos.close();
    }

    /** 数据读取 */
    @Override
    public Object load() throws IOException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(OBJECT_FILE));
        try {
            Object obj = ois.readObject();
            return obj;
        } catch (ClassNotFoundException e) {
            return null;
        } finally {
            ois.close();
        }
    }

    /** 根据用户查找信息 */
    @Override
    public void showByUser() throws IOException {
        Map<String, Object> map = (Map<String, Object>) this.load();
        User user = (User) map.get("yootk-zs");
        System.out.println(user);
        for (Role role : user.getRoles()) {
            System.out.println("\t|- " + role);
            for (Privilege privilege : role.getPrivileges()) {
                System.out.println("\t\t|- " + privilege);
            }
        }
    }

    /** 根据角色查找信息 */
    @Override
    public void showByRole() throws IOException {
        Map<String, Object> map = (Map<String, Object>) this.load();
        Role role = (Role) map.get("user");
        System.out.println(role);
        for (User user : role.getUsers()) {
            System.out.println("\t|- " + user);
        }
        for (Privilege privilege : role.getPrivileges()) {
            System.out.println("\t|- " + privilege);
        }
    }

    /** 根据权限查找信息 */
    @Override
    public void showByPrivilege() throws IOException {
        Map<String, Object> map = (Map<String, Object>) this.load();
        Privilege privilege = (Privilege) map.get("user:edit");
        System.out.println(privilege);
        System.out.println("\t|- " + privilege.getRole());
        for (User user : privilege.getRole().getUsers()) {
            System.out.println("\t\t|- " + user);
        }
    }
}
